package zhoug.common.clip;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.InputStream;
import java.io.OutputStream;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import zhoug.common.Extras;
import zhoug.common.R;
import zhoug.common.compat.BundleCompat;
import zhoug.common.compat.IBundle;
import zhoug.common.utils.BitmapUtils;
import zhoug.common.utils.StatusBarUtils;
import zhoug.logging.Logger;

/**
 * 裁剪图片
 *
 * @Author: 35574
 * @Date: 2022/7/22
 * @Description:
 */
public class ClipImageActivity extends AppCompatActivity {
    private static final String TAG = ">>>CutImageActivity";
    /**
     * 需要裁剪的图片路径
     */
    private static final String EXTRA_INPUT_DATA = Extras.Clip.EXTRA_INPUT_DATA;
    /**
     * 裁剪后输出图片存储地址
     */
    private static final String EXTRA_OUTPUT_DATA = Extras.Clip.EXTRA_OUTPUT_DATA;
    /**
     * 裁剪后输出图片存储格式,未设置outputData时自动生成路径时使用
     * {@link Bitmap.CompressFormat#JPEG#toString()}
     * {@link Bitmap.CompressFormat#PNG#toString()}
     * {@link Bitmap.CompressFormat#WEBP#toString()}
     */
    private static final String EXTRA_OUTPUT_FORMAT = Extras.Clip.EXTRA_OUTPUT_FORMAT;
    /**
     * 选择框是否可以拖动
     */
    private static final String EXTRA_FRAME_TRANS_ENABLE = Extras.Clip.EXTRA_FRAME_TRANS_ENABLE;
    /**
     * 选择框是否可以缩放
     */
    private static final String EXTRA_FRAME_SCALE_ENABLE = Extras.Clip.EXTRA_FRAME_SCALE_ENABLE;
    /**
     * 选择框默认宽高比
     */
    private static final String EXTRA_FRAME_RATIO = Extras.Clip.EXTRA_FRAME_RATIO;

    private Uri inputData;
    private Uri outputData;
    private Bitmap.CompressFormat outputFormat;
    private boolean frameTransEnable = true;
    private boolean frameScaleEnable = true;
    private float frameRatio = 0.75f;


    private TextView mBtnConfirm;
    private ImageView mBtnBack;
    private ClipImageView mClipImageView;
    private ClipFrameView mClipFrameView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.common_activity_cut_image);
        StatusBarUtils.setStatusBarColor(this, Color.BLACK);
        StatusBarUtils.setStatusBarTextColor(this, false, false);
        findViews();
        initParams();
        init();
        bindListener();
    }

    private void initParams() {
        Bundle extras = getIntent().getExtras();
        if (null != extras) {
            IBundle iBundle = BundleCompat.create(extras);
            inputData = iBundle.getParcelable(EXTRA_INPUT_DATA, Uri.class);
            outputData = iBundle.getParcelable(EXTRA_OUTPUT_DATA, Uri.class);
            String outputFormatName = iBundle.getString(EXTRA_OUTPUT_FORMAT);
            if (null != outputFormatName) {
                try {
                    outputFormat = Bitmap.CompressFormat.valueOf(outputFormatName.toUpperCase());
                } catch (IllegalArgumentException e) {
                    Logger.e(TAG, "initParams:" + e.getMessage());
                }
            }
            frameTransEnable = iBundle.getBoolean(EXTRA_FRAME_TRANS_ENABLE, true);
            frameScaleEnable = iBundle.getBoolean(EXTRA_FRAME_SCALE_ENABLE, true);
            frameRatio = iBundle.getFloat(EXTRA_FRAME_RATIO, 0.75f);
        }
        if(outputFormat==null){
            outputFormat= Bitmap.CompressFormat.JPEG;
        }
    }

    private void findViews() {
        mBtnConfirm = findViewById(R.id.btn_confirm);
        mBtnBack = findViewById(R.id.btn_back);
        mClipImageView = findViewById(R.id.clipImageView);
        mClipFrameView = findViewById(R.id.clipFrameView);
    }


    private void init() {
        mClipFrameView.setScaleEnabled(frameScaleEnable);
        mClipFrameView.setTranslateEnabled(frameTransEnable);
        mClipImageView.setFrameRatio(frameRatio);
        mClipImageView.setClipFrameView(mClipFrameView);
        if (null == inputData || outputData == null) {
            toastErrorAndFinish("inputData 和 outputData 不能为null");
            return;
        }
        try {
            InputStream inputStream = getContentResolver().openInputStream(inputData);
            Bitmap bitmap = BitmapUtils.decodeFile(inputStream, 1, Bitmap.Config.ARGB_8888);
            mClipImageView.setImageBitmap(bitmap);
        } catch (Exception e) {
            toastErrorAndFinish(e.getMessage());
        }
    }

    /**
     * 绑定监听器
     */
    private void bindListener() {
        mBtnBack.setOnClickListener(v -> finish());

        mBtnConfirm.setOnClickListener(v -> {
            Bitmap clipImage = null;
            try {
                clipImage = mClipImageView.getClipImage();
            } catch (Exception e) {
                Logger.e(TAG, e.getMessage());
            }
            if (clipImage == null) {
                toast("裁剪失败");
                return;
            }
            boolean b = false;
            try {
                OutputStream outputStream = getContentResolver().openOutputStream(outputData);

                b = BitmapUtils.keepBitmap(clipImage, 100, outputFormat, outputStream);
                if (b) {
                    Logger.d(TAG, "裁剪成功:");
                    Intent intent = new Intent();
                    setResult(RESULT_OK, intent);
                    finish();
                }
            } catch (Exception e) {
                Logger.e(TAG, e.getMessage());
            }

            if(!b){
                toastErrorAndFinish("保存裁剪后的图片失败");
            }
        });
    }




    private void toast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    /**
     * 显示错误并退出
     * @param error
     */
    private void toastErrorAndFinish(String error) {
        toast(error);
        Logger.e(TAG, error);
        setResult(RESULT_CANCELED);
        finish();
    }

}
